package com.sgb.kjwl.view.ui.activity.enterprise;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.text.Editable;
import android.text.InputFilter;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;

import androidx.databinding.DataBindingUtil;
import androidx.lifecycle.ViewModelProvider;

import com.bumptech.glide.Glide;
import com.google.gson.JsonObject;
import com.sgb.kjwl.AppActivity;
import com.sgb.kjwl.R;
import com.sgb.kjwl.databinding.ActivityAddNewQuoteBinding;
import com.sgb.kjwl.model.entity.transport.CargoPublishEntity;
import com.sgb.kjwl.utils.FileUtils;
import com.swgk.core.util.UiUtil;
import com.swgk.core.util.UserOperating;
import com.sgb.kjwl.view.widget.transport.AMapDialog;
import com.sgb.kjwl.viewmodel.enterprise.AddNeedQuoteModel;
import com.sgb.link.entity.AMapAddressEntity;
import com.swgk.core.dialog.DialogHelper;
import com.swgk.core.util.AttachmentStore;
import com.swgk.core.util.CheckUtils;
import com.swgk.core.util.ClickUtils;
import com.swgk.core.util.FileUtil;
import com.swgk.core.util.LogUtil;
import com.swgk.core.util.MToast;
import com.swgk.core.util.SharedPreferenceUtil;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

/**
 * Time:2021/7/12
 * Author:黄淋
 * Description:需求报价页面
 */
public class AddNeedQuoteActivity extends AppActivity {
    private ActivityAddNewQuoteBinding mBinding;
    private AddNeedQuoteModel mModel;
    //数据实体类
    private CargoPublishEntity.LocationEntity mEntity;
    // 打开文件管理器
    public static final int REQUESTCODE_OPEN_FILECHOOSER = 102;
    // 文件路径
    private String filePath;
    private String fileName;
    private String fileSize;
    private String fileType;
    private String mCurrentMain;//报价主体
    private String mAttachmentUrl;//附件地址格式化

    private String demandSide;
    private String demandTitle;
    private int demandId;
    private int requirementTypes;

    public static void start(Context context, String demandSide, String demandTitle, int demandId, int requirementTypes) {
        Intent intent = new Intent();
        intent.setClass(context, AddNeedQuoteActivity.class);
        intent.putExtra("demandSide", demandSide);
        intent.putExtra("demandTitle", demandTitle);
        intent.putExtra("demandId", demandId);
        intent.putExtra("requirementTypes", requirementTypes);
        context.startActivity(intent);
    }

    @Override
    protected void initView() {
        mBinding = DataBindingUtil.setContentView(this, R.layout.activity_add_new_quote);
        initListener();
        if (!"个人中心".equals(SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.COMPANY_NAME, ""))) {
            mCurrentMain = SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.COMPANY_NAME, "");
        } else {
            mCurrentMain = SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.REAL_NAME, "");
        }
        mBinding.tvinputtitle.setText(mCurrentMain);
    }

    @Override
    protected void init() {
        mModel = new ViewModelProvider(this).get(AddNeedQuoteModel.class);

        demandSide = getIntent().getStringExtra("demandSide");
        demandTitle = getIntent().getStringExtra("demandTitle");
        demandId = getIntent().getIntExtra("demandId", 0);
        requirementTypes = getIntent().getIntExtra("requirementTypes", 0);

        mModel.showLoading.observe(this, type -> {
            switch (type) {
                case 1:
                    DialogHelper.showProgressDialog(this, null, "数据加载中...", 0, false, null).setCanceledOnTouchOutside(false);
                    break;
                case 2:
                    DialogHelper.dismissProgressDialog();
                    break;
            }
        });
        mModel.toastUntil.observe(this, message -> {
            MToast.showLongToast(this, message);
        });
        mModel.stringLiveData.observe(this, this::setDemandAttachment);
        mModel.addQuoteLiveData.observe(this, a -> {
            if (a.equals("fail")) {
                finish();
                AddNeedQuoteResultActivity.start(this, false, false);
            } else {
                finish();
                AddNeedQuoteResultActivity.start(this, true, false);
            }
        });
        if (mBinding.actionBar != null) {
            mBinding.actionBar.setOnBackClickListener(v -> finish());
        }
    }

    /**
     * 设置监听
     */
    private void initListener() {
        mBinding.llToChooseLocation.setOnClickListener(this);
        mBinding.tvUploadAnnex.setOnClickListener(this);
        mBinding.tvUploadQuote.setOnClickListener(this);
        mBinding.tvAnnexDelete.setOnClickListener(this);

        mBinding.editMoney.addTextChangedListener(new TextWatcher() {
            @Override
            public void afterTextChanged(Editable editable) {
                String s = editable.toString();
                mBinding.editMoney.removeTextChangedListener(this);

                if (s.contains(".")) {
                    mBinding.editMoney.setFilters(new InputFilter[]{new InputFilter.LengthFilter(10 + 3 + 1)});
                    if (s.length() - 1 - s.indexOf(".") > 2) {
                        s = s.substring(0,
                                s.indexOf(".") + 2 + 1);
                        editable.replace(0, editable.length(), s.trim());
                    }
                } else {
                    mBinding.editMoney.setFilters(new InputFilter[]{new InputFilter.LengthFilter(10 + 1)});
                    if (s.length() > 10) {
                        s = s.substring(0, 10);
                        editable.replace(0, editable.length(), s.trim());
                    }
                }
                if (s.trim().equals(".")) {
                    s = "0" + s;
                    editable.replace(0, editable.length(), s.trim());
                }

                if (s.startsWith("0") && s.trim().length() > 1) {
                    if (!s.substring(1, 2).equals(".")) {
                        editable.replace(0, editable.length(), "0");
                    }
                }
                mBinding.editMoney.addTextChangedListener(this);
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int start, int before, int count) {

            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.ll_to_choose_location://选择联系地址
                AMapDialog.launch(this);
//                    AddNeedQuoteChooseLocationActivity.start(AddNeedQuoteActivity.this);

                break;
            case R.id.tv_upload_annex://上传文件
                if (!ClickUtils.isDoubleClick()) {
                    Intent fileIntent = new Intent(Intent.ACTION_GET_CONTENT);
                    fileIntent.addCategory(Intent.CATEGORY_OPENABLE);
                    //设置类型
                    fileIntent.setType("application/zip|image/png|application/pdf|application/rar|image/jpeg");
                    //在API>=19之后设置多个类型采用以下方式，setType不再支持多个类型
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                        fileIntent.putExtra(Intent.EXTRA_MIME_TYPES,
                                new String[]{"application/zip", "image/png", "application/pdf", "application/rar", "image/jpeg"});
                    }
                    startActivityForResult(fileIntent, REQUESTCODE_OPEN_FILECHOOSER);
                }
                break;
            case R.id.tv_annex_delete://删除附件
                if (!ClickUtils.isDoubleClick()) {
                    mAttachmentUrl = "";
                    fileName = "";
                    fileSize = "";
                    fileType = "";
                    mBinding.tvUploadAnnex.setVisibility(View.VISIBLE);
                    mBinding.rlAnnexInfo.setVisibility(View.GONE);
                }
                break;
            case R.id.tv_upload_quote://提交报价
                if (checkItemInput()) {
                    pushQuote();
                }
                break;
        }
    }

    /**
     * 检查必填项是否填写完整
     */
    private boolean checkItemInput() {
        if (TextUtils.isEmpty(mBinding.editMoney.getText().toString())) {
            MToast.showToast(this, "请输入报价金额！");
            return false;
        }
        if (TextUtils.isEmpty(mBinding.tvName.getText().toString())) {
            MToast.showToast(this, "请输入联系人");
            return false;
        }
        if (TextUtils.isEmpty(mBinding.etvContractPhone.getText().toString())) {
            MToast.showToast(this, "请输入联系电话");
            return false;
        }
        if (!CheckUtils.isMobileForService(mBinding.etvContractPhone.getText().toString())) {
            MToast.showToast(this, "请输入正确的电话格式");
            return false;
        }
        if (mBinding.etvContractLocation.getText().toString().equals("请选择联系地址")) {
            MToast.showToast(this, "请选择联系地址");
            return false;
        }
        if (!TextUtils.isEmpty(mBinding.etvMail.getText().toString())) { //邮箱
            if (!CheckUtils.isEmails(mBinding.etvMail.getText().toString())) {
                MToast.showToast(getActivity(), "请输入正确的邮箱地址");
                return false;
            }
        }
        return true;
    }

    /**
     * 提交报价
     */
    private void pushQuote() {
        Map<String, Object> map = new HashMap<>();
        map.put("offerSubject", mCurrentMain);
        map.put("address", mBinding.etvContractLocation.getText().toString());
        map.put("attachmentUrl", mAttachmentUrl);
        map.put("bidAmount", mBinding.editMoney.getText().toString());
        map.put("contact", mBinding.tvName.getText().toString());
        map.put("contactPhone", mBinding.etvContractPhone.getText().toString());
        map.put("email", mBinding.etvMail.getText().toString());
        if (mEntity != null) {
            map.put("latitude", mEntity.getLatitude());
            map.put("longitude", mEntity.getLongitude());
        }
        map.put("quotationNote", mBinding.etvQuoteDescription.getText().toString());
        map.put("publishType", UserOperating.getInstance().getUserIdentity());
        switch ((Integer) map.get("publishType")) {
            case 0:
                map.put("userNo", SharedPreferenceUtil.getInstance().getString(SharedPreferenceUtil.USER_NO, ""));
                break;
            case 1:
                map.put("companyNo", SharedPreferenceUtil.getInstance().getString(SharedPreferenceUtil.COMPANY_NO, ""));
                break;
            case 2:
                map.put("teamNo", SharedPreferenceUtil.getInstance().getString(SharedPreferenceUtil.COMPANY_NO, ""));
                break;
        }
        map.put("demandSide", demandSide);
        map.put("demandTitle", demandTitle);
        map.put("demandId", demandId);
        map.put("requirementTypes", requirementTypes);
        map.put("userAccount", SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.LOGIN_PHONE, ""));

        mModel.uploadQuote(map);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode != RESULT_OK) return;
        if (requestCode == REQUESTCODE_OPEN_FILECHOOSER) {//选择文件返回
            if (data == null) {
                LogUtil.d("TAG", "onActivityResult chooseFile data is null");
                return;
            }
            handleFileChoose(data);
        } else {
            AMapAddressEntity entity = AMapDialog.get(data);
            if (entity != null) {
                mBinding.etvContractLocation.setText(String.format("%s%s%s%s",
                        entity.getProvince(),
                        entity.getCity(),
                        entity.getDistrict(),
                        entity.getSnippet()));
                mBinding.etvContractLocation.setTextColor(getResources().getColor(R.color.color_333333));
                //设置数据
                mEntity = new CargoPublishEntity.LocationEntity();
                mEntity.setLatitude(entity.getLatitude());
                mEntity.setLongitude(entity.getLongitude());
                mEntity.setProvince(entity.getProvince());
                mEntity.setCity(entity.getCity());
                mEntity.setDistrict(entity.getDistrict());
                mEntity.setProvinceNo(entity.getProvinceNo());
                mEntity.setCityNo(entity.getCityNo());
                mEntity.setDistrictNo(entity.getDistrictNo());
                mEntity.setAddress(entity.getSnippet());
            }
        }
    }

    private void handleFileChoose(Intent data) {
        Uri uri = data.getData();
//        binding.rlFilename.setVisibility(View.VISIBLE);
        /****
         * //使用第三方应用打开
         */
        if ("file".equalsIgnoreCase(uri.getScheme())) {
            filePath = uri.getPath();
            if (checkFileSize(filePath)) {
                mBinding.tvUploadAnnex.setVisibility(View.GONE);
                mBinding.rlAnnexInfo.setVisibility(View.VISIBLE);
                fileName = new File(filePath).getName();
                long fileLength = AttachmentStore.getFileLength(filePath);
                fileSize = UiUtil.bytes2kb(fileLength);
                fileType = FileUtil.getMimeType(new File(filePath));
                mBinding.tvAnnexName.setText(fileName);
                mBinding.tvAnnexSize.setText(fileSize);
                switch (fileType) {
                    case "application/zip":
                    case "application/rar":
                        Glide.with(this).load(R.mipmap.icon_zip).into(mBinding.ivAnnexSimple);
                        break;
                    case "image/png":
                    case "image/jpeg":
                        Glide.with(this).load(R.mipmap.icon_image).into(mBinding.ivAnnexSimple);
                        break;
                    case "application/pdf":
                        Glide.with(this).load(R.mipmap.icon_pdf2).into(mBinding.ivAnnexSimple);
                        break;
                }
                mModel.uploadSingleImage(this, new File(filePath), 1, true);
            }
            LogUtil.d("TAG", "handleFileChoose uri.getScheme():" + filePath);
            return;
        }
        /***
         * //4.4以后
         */
        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.KITKAT) {
            filePath = FileUtils.getPath(this, uri);
        } else {//4.4以下下系统调用方法
            filePath = FileUtils.getRealPathFromURI(uri, this);
        }
        if (checkFileSize(filePath)) {
            mBinding.tvUploadAnnex.setVisibility(View.GONE);
            mBinding.rlAnnexInfo.setVisibility(View.VISIBLE);
            fileName = new File(filePath).getName();
            long fileLength = AttachmentStore.getFileLength(filePath);
            fileSize = UiUtil.bytes2kb(fileLength);
            fileType = FileUtil.getMimeType(new File(filePath));
            mBinding.tvAnnexName.setText(fileName);
            mBinding.tvAnnexSize.setText(fileSize);
            switch (fileType) {
                case "application/zip":
                case "application/rar":
                    Glide.with(this).load(R.mipmap.icon_zip).into(mBinding.ivAnnexSimple);
                    break;
                case "image/png":
                case "image/jpeg":
                    Glide.with(this).load(R.mipmap.icon_image).into(mBinding.ivAnnexSimple);
                    break;
                case "application/pdf":
                    Glide.with(this).load(R.mipmap.icon_pdf2).into(mBinding.ivAnnexSimple);
                    break;
            }
            mModel.uploadSingleImage(this, new File(filePath), 1, true);
        }
        LogUtil.d("TAG", "handleFileChoose filePath:" + filePath);
    }

    /**
     * 检查文件大小
     *
     * @param filePath 文件路径
     * @return 文件大小
     */
    private boolean checkFileSize(String filePath) {
        float sizeCount = 0f;
        long fileLength = AttachmentStore.getFileLength(filePath);
        String fileSize = FileUtil.formatFileSize(fileLength, FileUtil.SizeUnit.MB);
        if (fileSize.contains("MB")) {
            String fileSizeCount = fileSize.replace("MB", "");
            if (!TextUtils.isEmpty(fileSizeCount)) {
                sizeCount = Float.parseFloat(fileSizeCount);
                if (sizeCount > 50) {
                    MToast.showToast(this, "请上传50MB内的文件！");
                    return false;
                }
            }
        }
        return true;
    }

    private void setDemandAttachment(String fileUrl) {
        if (!TextUtils.isEmpty(fileUrl)) {
            JsonObject jsonObject = new JsonObject();
            jsonObject.addProperty("name", fileName);
            jsonObject.addProperty("url", fileUrl);
            jsonObject.addProperty("size", fileSize);
            jsonObject.addProperty("type", fileType);
            mAttachmentUrl = jsonObject.toString();
        }
    }
}
